@{
    ViewData["Title"] = "任务管理";
}

<style>
    .layui-card {
        margin: 15px;
    }
    
    .layui-card-header {
        background: linear-gradient(135deg, #1E9FFF 0%, #009688 100%);
        color: white;
        border-radius: 4px 4px 0 0;
    }
    
    .layui-form-label {
        width: 120px;
        font-weight: 600;
        color: #333;
    }
    
    .layui-input-block {
        margin-left: 120px;
    }
    
    .layui-input {
        border-radius: 4px;
        border: 1px solid #e6e6e6;
        transition: all 0.3s;
    }
    
    .layui-input:focus {
        border-color: #1E9FFF;
        box-shadow: 0 0 0 2px rgba(30, 159, 255, 0.2);
    }
    
    .layui-btn {
        border-radius: 4px;
        margin: 0 5px;
        padding: 8px 20px;
        font-weight: 500;
    }
    
    .layui-btn-normal {
        background: linear-gradient(135deg, #1E9FFF 0%, #009688 100%);
        border: none;
    }
    
    .layui-btn-primary {
        background: linear-gradient(135deg, #5FB878 0%, #009688 100%);
        border: none;
        color: white;
    }
    
    .layui-table {
        border-radius: 4px;
        overflow: hidden;
    }
    
    .layui-table th {
        background: #f8f9fa;
        font-weight: 600;
        color: #333;
    }
    
    .layui-table td {
        vertical-align: middle;
    }
    
    .layui-badge {
        margin: 2px;
        font-size: 11px;
        padding: 4px 8px;
        border-radius: 12px;
    }
    
    .layui-bg-blue {
        background-color: #1E9FFF !important;
    }
    
    .layui-bg-green {
        background-color: #5FB878 !important;
    }
    
    .layui-bg-orange {
        background-color: #FFB800 !important;
        color: #333 !important;
    }
    
    .layui-bg-gray {
        background-color: #999 !important;
    }
</style>

<div class="layui-card">
    <div class="layui-card-header">
        <h3 style="margin: 0; color: white;">
            <i class="layui-icon layui-icon-list" style="font-size: 18px; margin-right: 8px;"></i>
            任务管理
        </h3>
    </div>
    <div class="layui-card-body">
        <!-- 搜索区域 -->
        <div class="layui-row layui-form" style="margin-bottom: 15px;">
            <div class="layui-col-md3">
                <div class="layui-form-item">
                    <label class="layui-form-label">工单编号:</label>
                    <div class="layui-input-block">
                        <input type="text" id="workOrderNumber" placeholder="请输入工单编号" class="layui-input">
                    </div>
                </div>
            </div>
            <div class="layui-col-md3">
                <div class="layui-form-item">
                    <label class="layui-form-label">工序名称:</label>
                    <div class="layui-input-block">
                        <input type="text" id="processName" placeholder="请输入工序名称" class="layui-input">
                    </div>
                </div>
            </div>
            <div class="layui-col-md3">
                <div class="layui-form-item">
                    <label class="layui-input-block" style="margin-left: 0;">
                        <button type="button" class="layui-btn layui-btn-normal" onclick="queryWorkTask()">
                            <i class="layui-icon layui-icon-search"></i> 查询
                        </button>
                        <button type="button" class="layui-btn layui-btn-primary" onclick="showAdvancedQuery()">
                            <i class="layui-icon layui-icon-search"></i> 高级查询
                        </button>
                    </label>
                </div>
            </div>
        </div>

        <!-- 操作按钮区域 -->
        <div class="layui-row" style="margin-bottom: 15px;">
            <div class="layui-col-md12">
                <div class="layui-btn-group" style="margin-right: 10px;">
                    <button type="button" class="layui-btn layui-btn-normal" onclick="addWorkTask()">
                        <i class="layui-icon layui-icon-add-1"></i> 新建
                    </button>
                    <button type="button" class="layui-btn layui-btn-warm" onclick="editWorkTask()">
                        <i class="layui-icon layui-icon-edit"></i> 编辑
                    </button>
                    <button type="button" class="layui-btn layui-btn-danger" onclick="deleteWorkTask()">
                        <i class="layui-icon layui-icon-delete"></i> 删除
                    </button>
                </div>
                
                <div class="layui-btn-group" style="margin-right: 10px;">
                    <button type="button" class="layui-btn layui-btn-normal" onclick="importWorkTask()">
                        <i class="layui-icon layui-icon-upload"></i> 导入
                    </button>
                    <button type="button" class="layui-btn layui-btn-normal" onclick="exportWorkTask()">
                        <i class="layui-icon layui-icon-download-circle"></i> 导出
                    </button>
                </div>
                
                <div class="layui-btn-group" style="margin-right: 10px;">
                    <button type="button" class="layui-btn layui-btn-primary" onclick="resetForm()">
                        <i class="layui-icon layui-icon-refresh"></i> 重置
                    </button>
                </div>
                
                <div class="layui-btn-group">
                    <button type="button" class="layui-btn layui-btn-warm" onclick="testApi()">
                        <i class="layui-icon layui-icon-search"></i> 测试API
                    </button>
                    <button type="button" class="layui-btn layui-btn-normal" onclick="loadWorkTaskData()">
                        <i class="layui-icon layui-icon-refresh"></i> 重新加载
                    </button>
                    <button type="button" class="layui-btn layui-btn-danger" onclick="testLayer()">
                        <i class="layui-icon layui-icon-close"></i> 测试弹窗
                    </button>
                </div>
            </div>
        </div>

        <!-- 任务列表表格 -->
        <table class="layui-table" lay-even lay-skin="row" id="workTaskTable">
            <thead>
                <tr>
                    <th style="width: 60px;">
                        <input type="checkbox" lay-skin="primary" lay-filter="allSelect" id="allSelectCheckbox" onchange="handleAllSelect(this)">
                    </th>
                    <th>工序名称</th>
                    <th>工序编号</th>
                    <th>报工权限</th>
                    <th>报工数配比</th>
                    <th>不良品项列表</th>
                    <th>分配列表</th>
                    <th>计划开始时间</th>
                    <th>计划结束时间</th>
                    <th>计划数量</th>
                    <th>良品数量</th>
                    <th>不良品数量</th>
                    <th>状态</th>
                    <th>创建时间</th>
                </tr>
            </thead>
            <tbody id="workTaskTableBody">
                <tr>
                    <td colspan="14" style="text-align: center; color: #999;">暂无数据</td>
                </tr>
            </tbody>
        </table>

        <!-- 分页 -->
        <div id="pagination" style="text-align: center;"></div>
    </div>
</div>

<!-- 编辑任务弹窗 -->
<div id="editWorkTaskModal" style="display: none; padding: 20px;">
    <form class="layui-form" id="editWorkTaskForm">
        <div class="layui-row">
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">工序名称:</label>
                    <div class="layui-input-block">
                        <input type="text" id="editProcessName" class="layui-input" readonly>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">工序编号:</label>
                    <div class="layui-input-block">
                        <input type="text" id="editProcessNumber" class="layui-input" readonly>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="layui-row">
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">报工权限:</label>
                    <div class="layui-input-block">
                        <input type="text" id="editReportingPermissions" class="layui-input" placeholder="点击选择报工权限" readonly onclick="showRoleSelectModal()">
                        <input type="hidden" id="editReportingPermissionsIds">
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">报工数配比:</label>
                    <div class="layui-input-block">
                        <input type="number" id="editReportingRatio" class="layui-input" min="0">
                    </div>
                </div>
            </div>
        </div>
        
        <div class="layui-row">
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">计划数量:</label>
                    <div class="layui-input-block">
                        <input type="number" id="editPlannedQuantity" class="layui-input" min="0">
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">分配列表:</label>
                    <div class="layui-input-block">
                        <input type="text" id="editAllocationList" class="layui-input">
                    </div>
                </div>
            </div>
        </div>
        
        <div class="layui-row">
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">计划开始时间:</label>
                    <div class="layui-input-block">
                        <input type="text" id="editPlannedStartTime" class="layui-input" placeholder="请选择计划开始时间" onclick="layui.laydate.render({elem: '#editPlannedStartTime', type: 'datetime'})">
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">计划结束时间:</label>
                    <div class="layui-input-block">
                        <input type="text" id="editPlannedEndTime" class="layui-input" placeholder="请选择计划结束时间" onclick="layui.laydate.render({elem: '#editPlannedEndTime', type: 'datetime'})">
                    </div>
                </div>
            </div>
        </div>
        
        <div class="layui-row">
            <div class="layui-col-md12">
                <div class="layui-form-item">
                    <label class="layui-form-label">不良品项列表:</label>
                    <div class="layui-input-block">
                        <input type="text" id="editDefectiveItemList" class="layui-input" placeholder="点击选择不良品项" readonly onclick="showDefectiveSelectModal()">
                        <input type="hidden" id="editDefectiveItemIds">
                    </div>
                </div>
            </div>
        </div>
        
        <div class="layui-row">
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">良品数量:</label>
                    <div class="layui-input-block">
                        <input type="number" id="editGoodQuantity" class="layui-input" min="0" readonly>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">不良品数量:</label>
                    <div class="layui-input-block">
                        <input type="number" id="editDefectiveQuantity" class="layui-input" min="0" readonly>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="layui-row">
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">实际开始时间:</label>
                    <div class="layui-input-block">
                        <input type="text" id="editActualStartTime" class="layui-input" readonly>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">实际结束时间:</label>
                    <div class="layui-input-block">
                        <input type="text" id="editActualEndTime" class="layui-input" readonly>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="layui-row">
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">创建时间:</label>
                    <div class="layui-input-block">
                        <input type="text" id="editCreationTime" class="layui-input" readonly>
                    </div>
                </div>
            </div>
            <div class="layui-col-md6">
                <div class="layui-form-item">
                    <label class="layui-form-label">创建人:</label>
                    <div class="layui-input-block">
                        <input type="text" id="editCreator" class="layui-input" readonly>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="layui-form-item" style="text-align: center; margin-top: 30px;">
            <button type="button" class="layui-btn layui-btn-normal" onclick="saveEditWorkTask()">
                <i class="layui-icon layui-icon-ok"></i> 保存
            </button>
            <button type="button" class="layui-btn layui-btn-primary" onclick="closeEditModal()">
                <i class="layui-icon layui-icon-close"></i> 关闭
            </button>
        </div>
    </form>
</div>

<!-- 角色选择弹窗 -->
<div id="roleSelectModal" style="display: none; padding: 20px;">
    <h3>选择报工权限</h3>
    <div id="roleList" style="max-height: 300px; overflow-y: auto; margin: 15px 0;">
        <!-- 角色列表将通过JavaScript动态生成 -->
    </div>
    <div style="text-align: center; margin-top: 20px;">
        <button type="button" class="layui-btn layui-btn-normal" onclick="confirmRoleSelection()">确定</button>
        <button type="button" class="layui-btn layui-btn-primary" onclick="closeRoleSelectModal()">取消</button>
    </div>
</div>

<!-- 不良品项选择弹窗 -->
<div id="defectiveSelectModal" style="display: none; padding: 20px;">
    <h3>选择不良品项</h3>
    <div id="defectiveList" style="max-height: 300px; overflow-y: auto; margin: 15px 0;">
        <!-- 不良品项列表将通过JavaScript动态生成 -->
    </div>
    <div style="text-align: center; margin-top: 20px;">
        <button type="button" class="layui-btn layui-btn-normal" onclick="confirmDefectiveSelection()">确定</button>
        <button type="button" class="layui-btn layui-btn-primary" onclick="closeDefectiveSelectModal()">取消</button>
    </div>
</div>

<script>
// 全局变量
var currentPage = 1;
var pageSize = 30;
var totalCount = 0;
var selectedWorkTaskIds = [];

// 查询任务
function queryWorkTask() {
    currentPage = 1;
    loadWorkTaskData();
}

// 加载任务数据
function loadWorkTaskData() {
    console.log('开始加载任务数据...');
    
    var queryData = {
        pageIndex: currentPage,
        pageSize: pageSize,
        workOrderNumber: document.getElementById('workOrderNumber').value,
        processName: document.getElementById('processName').value,
        processNumber: '',
        defectiveItemList: '',
        plannedStartTimeStart: null,
        plannedStartTimeEnd: null,
        plannedEndTimeStart: null,
        plannedEndTimeEnd: null,
        plannedQuantityMin: null,
        plannedQuantityMax: null,
        goodQuantityMin: null,
        goodQuantityMax: null,
        defectiveQuantityMin: null,
        defectiveQuantityMax: null,
        actualStartTimeStart: null,
        actualStartTimeEnd: null,
        actualEndTimeStart: null,
        actualEndTimeEnd: null,
        creationTimeStart: null,
        creationTimeEnd: null,
        sortField: 'Id',
        sortDirection: 'desc'
    };
    
    console.log('查询参数:', queryData);
    console.log('调用API: /WorkTask/GetWorkTaskPage');
    
    fetch('/WorkTask/GetWorkTaskPage', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(queryData)
    })
    .then(response => {
        console.log('API响应状态:', response.status);
        console.log('API响应头:', response.headers);
        
        // 先获取响应文本，然后尝试解析JSON
        return response.text().then(text => {
            console.log('API原始响应:', text);
            
            // 尝试解析JSON
            try {
                if (text && text.trim()) {
                    return JSON.parse(text);
                } else {
                    console.error('API响应为空，无法获取数据');
                    throw new Error('API响应为空');
                }
            } catch (parseError) {
                console.error('JSON解析失败:', parseError);
                throw new Error('API响应格式错误');
            }
        });
    })
    .then(data => {
        console.log('API返回数据:', data);
        if (data.code === 200) {
            console.log('查询成功，数据:', data.data);
            renderWorkTaskTable(data.data.data);
            totalCount = data.data.total;
            renderPagination();
        } else {
            console.error('查询失败:', data.msg);
            layui.use(['layer'], function(){
                var layer = layui.layer;
                layer.msg(data.msg || '查询失败');
            });
        }
    })
    .catch(error => {
        console.error('查询异常:', error);
        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.msg('查询失败: ' + error.message);
        });
    });
}

// 渲染任务表格
function renderWorkTaskTable(data) {
    var tbody = document.getElementById('workTaskTableBody');
    tbody.innerHTML = '';
    
    if (data && data.length > 0) {
        data.forEach((task, index) => {
            var row = document.createElement('tr');
            row.setAttribute('data-task-id', task.id);
            
            row.innerHTML = `
                <td>
                    <input type="checkbox" lay-skin="primary" lay-filter="workTaskSelect" value="${task.id}" onchange="handleTaskSelect(this, ${task.id})">
                </td>
                <td><a href="javascript:;" onclick="editWorkTaskById(${task.id})" style="color: #1E9FFF; text-decoration: underline;">${task.processName || ''}</a></td>
                <td>${task.processNumber || ''}</td>
                <td>${formatReportingPermissions(task.reportingPermissions)}</td>
                <td>${task.reportingRatio || ''}</td>
                <td>${formatDefectiveItemList(task.defectiveItemList)}</td>
                <td>${task.allocationList || ''}</td>
                <td>${formatDateTime(task.plannedStartTime)}</td>
                <td>${formatDateTime(task.plannedEndTime)}</td>
                <td>${task.plannedQuantity || 0}</td>
                <td>${task.goodQuantity || 0}</td>
                <td>${task.defectiveQuantity || 0}</td>
                <td>${task.status || '待处理'}</td>
                <td>${formatDateTime(task.creatorDate)}</td>
            `;
            
            tbody.appendChild(row);
        });
        
        // 重置全选状态
        updateAllSelectStatus();
    } else {
        tbody.innerHTML = '<tr><td colspan="14" style="text-align: center; color: #999;">暂无数据</td></tr>';
        // 清空选中的任务ID
        selectedWorkTaskIds = [];
        // 重置全选复选框
        updateAllSelectStatus();
    }
    
    // 重新渲染表单
    layui.form.render();
}

// 渲染分页
function renderPagination() {
    var totalPages = Math.ceil(totalCount / pageSize);
    var pagination = document.getElementById('pagination');
    
    if (totalPages <= 1) {
        pagination.innerHTML = '';
        return;
    }
    
    var html = `
        <div class="layui-box layui-laypage layui-laypage-default">
            <span class="layui-laypage-count">共${totalCount}条</span>
            <select lay-filter="pageSize" style="margin: 0 10px;">
                <option value="10" ${pageSize === 10 ? 'selected' : ''}>10条/页</option>
                <option value="30" ${pageSize === 30 ? 'selected' : ''}>30条/页</option>
                <option value="50" ${pageSize === 50 ? 'selected' : ''}>50条/页</option>
                <option value="100" ${pageSize === 100 ? 'selected' : ''}>100条/页</option>
            </select>
    `;
    
    if (currentPage > 1) {
        html += `<a href="javascript:;" onclick="goToPage(${currentPage - 1})" class="layui-laypage-prev">上一页</a>`;
    }
    
    for (var i = 1; i <= totalPages; i++) {
        if (i === currentPage) {
            html += `<span class="layui-laypage-curr"><em class="layui-laypage-em"></em><em>${i}</em></span>`;
        } else {
            html += `<a href="javascript:;" onclick="goToPage(${i})">${i}</a>`;
        }
    }
    
    if (currentPage < totalPages) {
        html += `<a href="javascript:;" onclick="goToPage(${currentPage + 1})" class="layui-laypage-next">下一页</a>`;
    }
    
    html += `
            <span class="layui-laypage-skip">
                前往<input type="text" class="layui-input" id="goToPageInput" style="width: 50px; display: inline-block;">页
                <button type="button" class="layui-btn layui-btn-sm" onclick="goToPageInput()">确定</button>
            </span>
        </div>
    `;
    
    pagination.innerHTML = html;
    
    // 重新渲染表单
    layui.form.render();
}

// 跳转到指定页
function goToPage(page) {
    if (page < 1) return;
    currentPage = page;
    loadWorkTaskData();
}

// 输入页码跳转
function goToPageInput() {
    var input = document.getElementById('goToPageInput');
    var page = parseInt(input.value);
    if (page && page > 0) {
        goToPage(page);
    }
}

// 选择任务
function selectWorkTask(taskId) {
    // 移除其他行的选中状态
    var rows = document.querySelectorAll('#workTaskTableBody tr');
    rows.forEach(row => {
        row.style.backgroundColor = '';
    });
    
    // 设置当前行选中状态
    event.target.closest('tr').style.backgroundColor = '#e6f3ff';
}

// 显示高级查询弹窗
function showAdvancedQuery() {
    layui.use(['layer'], function(){
        var layer = layui.layer;
        layer.msg('高级查询功能待实现');
    });
}

// 重置表单
function resetForm() {
    document.getElementById('workOrderNumber').value = '';
    document.getElementById('processName').value = '';
    
    // 重新加载数据
    loadWorkTaskData();
}

// 新建任务
function addWorkTask() {
    layui.use(['layer'], function(){
        var layer = layui.layer;
        layer.msg('新建任务功能待实现');
    });
}

// 编辑任务
function editWorkTask() {
    if (selectedWorkTaskIds.length === 0) {
        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.msg('请先选择要编辑的任务');
        });
        return;
    }
    layui.use(['layer'], function(){
        var layer = layui.layer;
        layer.msg('编辑任务功能待实现');
    });
}

// 删除任务
function deleteWorkTask() {
    console.log('删除任务 - 当前选中的任务ID:', selectedWorkTaskIds);
    console.log('删除任务 - 选中数量:', selectedWorkTaskIds.length);
    
    if (!selectedWorkTaskIds || selectedWorkTaskIds.length === 0) {
        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.msg('请先选择要删除的任务');
        });
        return;
    }
    
    // 显示确认删除对话框
    layui.use(['layer'], function(){
        var layer = layui.layer;
        layer.confirm(
            `确定要删除选中的 ${selectedWorkTaskIds.length} 个任务吗？<br><br><span style="color: #ff5722; font-weight: bold;">此操作不可恢复！</span>`, 
            {
                title: '确认删除',
                icon: 3,
                btn: ['确定删除', '取消'],
                btnAlign: 'c',
                shade: 0.3,
                shadeClose: false
            }, 
            function(index) {
                // 用户确认删除
                executeDeleteWorkTask();
                layer.close(index);
            },
            function(index) {
                // 用户取消删除
                layer.close(index);
            }
        );
    });
}

// 执行删除任务
function executeDeleteWorkTask() {
    if (selectedWorkTaskIds.length === 0) {
        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.msg('没有选中的任务');
        });
        return;
    }
    
    // 显示加载提示
    layui.use(['layer'], function(){
        var layer = layui.layer;
        var loadIndex = layer.load(1, {
            shade: [0.3, '#000']
        });
        
        // 将loadIndex保存到全局变量，以便后续使用
        window.currentLoadIndex = loadIndex;
    });
    
    // 构建删除请求
    var deleteRequest = {
        ids: selectedWorkTaskIds,
        deleter: 'admin' // 这里可以从session获取当前用户
    };
    
    console.log('删除请求:', deleteRequest);
    
    fetch('/WorkTask/BatchDelete', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(deleteRequest)
    })
    .then(response => {
        console.log('删除API响应状态:', response.status);
        console.log('删除API响应头:', response.headers);
        
        // 先获取响应文本，然后尝试解析JSON
        return response.text().then(text => {
            console.log('删除API原始响应:', text);
            
            // 尝试解析JSON
            try {
                if (text && text.trim()) {
                    return JSON.parse(text);
                } else {
                    throw new Error('响应内容为空');
                }
            } catch (parseError) {
                console.error('JSON解析失败:', parseError);
                throw new Error(`响应格式错误: ${text}`);
            }
        });
    })
    .then(data => {
        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.close(window.currentLoadIndex);
            console.log('删除API返回数据:', data);
            
            if (data.code === 200) {
                layer.msg('删除成功！', {icon: 1, time: 2000});
                
                // 清空选中的任务ID
                selectedWorkTaskIds = [];
                
                // 重置全选复选框
                document.getElementById('allSelectCheckbox').checked = false;
                
                // 刷新任务列表
                loadWorkTaskData();
            } else {
                layer.msg('删除失败：' + (data.msg || '未知错误'), {icon: 2, time: 3000});
            }
        });
    })
    .catch(error => {
        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.close(window.currentLoadIndex);
            console.error('删除异常:', error);
            layer.msg('删除失败：' + error.message, {icon: 2, time: 3000});
        });
    });
}

// 导入任务
function importWorkTask() {
    layui.use(['layer'], function(){
        var layer = layui.layer;
        layer.msg('导入任务功能待实现');
    });
}

// 导出任务
function exportWorkTask() {
    layui.use(['layer'], function(){
        var layer = layui.layer;
        layer.msg('导出任务功能待实现');
    });
}

// 处理全选事件
function handleAllSelect(checkbox) {
    console.log('handleAllSelect 被调用:', checkbox.checked);
    
    var checkboxes = document.querySelectorAll('#workTaskTableBody input[type="checkbox"]');
    var isChecked = checkbox.checked;
    
    // 清空当前选中的任务ID
    selectedWorkTaskIds = [];
    
    // 更新所有复选框状态并收集选中的任务ID
    checkboxes.forEach(checkbox => {
        checkbox.checked = isChecked;
        if (isChecked && checkbox.value && checkbox.value !== '') {
            selectedWorkTaskIds.push(parseInt(checkbox.value));
        }
    });
    
    console.log('全选处理完成 - 选中数量:', selectedWorkTaskIds.length, '选中的任务ID:', selectedWorkTaskIds);
}

// 处理任务选择事件
function handleTaskSelect(checkbox, taskId) {
    console.log('handleTaskSelect 被调用:', checkbox.checked, '任务ID:', taskId);
    
    if (checkbox.checked) {
        if (!selectedWorkTaskIds.includes(taskId)) {
            selectedWorkTaskIds.push(taskId);
        }
    } else {
        selectedWorkTaskIds = selectedWorkTaskIds.filter(id => id !== taskId);
    }
    
    // 检查是否需要更新全选状态
    updateAllSelectStatus();
    
    console.log('单个选择处理完成 - 选中数量:', selectedWorkTaskIds.length, '当前选中数组:', selectedWorkTaskIds);
}

// 更新全选状态
function updateAllSelectStatus() {
    var allSelectCheckbox = document.getElementById('allSelectCheckbox');
    var checkboxes = document.querySelectorAll('#workTaskTableBody input[type="checkbox"]');
    
    if (checkboxes.length === 0) {
        allSelectCheckbox.checked = false;
        allSelectCheckbox.indeterminate = false;
        return;
    }
    
    var checkedCount = 0;
    checkboxes.forEach(checkbox => {
        if (checkbox.checked) {
            checkedCount++;
        }
    });
    
    if (checkedCount === 0) {
        // 没有选中任何项
        allSelectCheckbox.checked = false;
        allSelectCheckbox.indeterminate = false;
    } else if (checkedCount === checkboxes.length) {
        // 全部选中
        allSelectCheckbox.checked = true;
        allSelectCheckbox.indeterminate = false;
    } else {
        // 部分选中
        allSelectCheckbox.checked = false;
        allSelectCheckbox.indeterminate = true;
    }
}

// 测试API
function testApi() {
    console.log('=== 开始测试API ===');
    
    // 测试1: 检查页面元素
    console.log('页面元素检查:');
    console.log('- 工单编号输入框:', document.getElementById('workOrderNumber'));
    console.log('- 工序名称输入框:', document.getElementById('processName'));
    console.log('- 任务表格:', document.getElementById('workTaskTable'));
    console.log('- 表格体:', document.getElementById('workTaskTableBody'));
    
    // 测试2: 测试MVC控制器
    console.log('测试MVC控制器...');
    fetch('/WorkTask/GetWorkTaskPage', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            pageIndex: 1,
            pageSize: 10,
            workOrderNumber: '',
            processName: '',
            sortField: 'Id',
            sortDirection: 'desc'
        })
    })
    .then(response => {
        console.log('MVC控制器响应状态:', response.status);
        console.log('MVC控制器响应头:', response.headers);
        return response.text();
    })
    .then(data => {
        console.log('MVC控制器返回数据:', data);
        try {
            var jsonData = JSON.parse(data);
            console.log('解析后的JSON数据:', jsonData);
        } catch (e) {
            console.log('数据不是有效的JSON格式');
        }
    })
    .catch(error => {
        console.error('MVC控制器调用失败:', error);
    });
    
    // 测试3: 测试角色API
    console.log('测试角色API...');
    fetch('/WorkTask/GetRoleAll')
        .then(response => response.text())
        .then(data => {
            console.log('角色API返回数据:', data);
        })
        .catch(error => {
            console.error('角色API调用失败:', error);
        });
    
    // 测试4: 测试不良品项API
    console.log('测试不良品项API...');
    fetch('/WorkTask/GetDefectiveList?index=1&size=10')
        .then(response => response.text())
        .then(data => {
            console.log('不良品项API返回数据:', data);
        })
        .catch(error => {
            console.error('不良品项API调用失败:', error);
        });
    
    console.log('=== API测试完成 ===');
}

// 测试弹窗功能
function testLayer() {
    console.log('开始测试弹窗功能...');
    console.log('Layui对象:', layui);
    console.log('当前页面Layui状态:', typeof layui);
    
    // 检查Layui是否可用
    if (typeof layui === 'undefined') {
        alert('Layui未加载，请检查页面引用');
        return;
    }
    
    // 检查layer模块是否可用
    if (typeof layui.layer === 'undefined') {
        console.log('Layer模块未直接可用，尝试使用layui.use加载');
        
        layui.use(['layer'], function(){
            var layer = layui.layer;
            console.log('Layer模块加载成功:', layer);
            
            if (layer && typeof layer.open === 'function') {
                // 测试简单弹窗
                var index = layer.open({
                    type: 1,
                    title: '测试弹窗',
                    content: '<div style="padding: 20px;">这是一个测试弹窗，用于验证Layui是否正常工作</div>',
                    area: ['400px', '200px'],
                    success: function(layero, index) {
                        console.log('测试弹窗显示成功，索引:', index);
                    }
                });
                
                console.log('测试弹窗索引:', index);
            } else {
                alert('Layer模块加载失败，layer.open方法不可用');
            }
        });
    } else {
        console.log('Layer模块直接可用:', layui.layer);
        
        // 直接使用layer
        var index = layui.layer.open({
            type: 1,
            title: '测试弹窗',
            content: '<div style="padding: 20px;">这是一个测试弹窗，用于验证Layui是否正常工作</div>',
            area: ['400px', '200px'],
            success: function(layero, index) {
                console.log('测试弹窗显示成功，索引:', index);
            }
        });
        
        console.log('测试弹窗索引:', index);
    }
}

// 格式化报工权限
function formatReportingPermissions(permissionsStr) {
    if (!permissionsStr) return '';
    const permissions = permissionsStr.split(',').map(s => s.trim()).filter(Boolean);
    if (permissions.length === 0) return '';
    
    const labels = permissions.map(permission => {
        if (permission === '所有人') {
            return '<span class="layui-badge layui-bg-blue">所有人</span>';
        }
        return `<span class="layui-badge layui-bg-green">${permission}</span>`;
    });
    return labels.join(' ');
}

// 格式化不良品项列表
function formatDefectiveItemList(defectiveItemList) {
    if (!defectiveItemList) return '';
    
    try {
        const items = defectiveItemList.split(',').map(s => s.trim()).filter(Boolean);
        if (items.length === 0) return '';
        
        const displayItems = items.map(item => {
            if (item.includes('|')) {
                const [code, name] = item.split('|').map(s => s.trim());
                return `<span class="layui-badge layui-bg-orange">${code} | ${name}</span>`;
            }
            return `<span class="layui-badge layui-bg-gray">${item}</span>`;
        });
        
        return displayItems.join(' ');
    } catch (e) {
        console.error('格式化不良品项列表出错:', e);
        return defectiveItemList;
    }
}

// 格式化日期时间
function formatDateTime(dateTime) {
    if (!dateTime) return '-';
    
    try {
        var date = new Date(dateTime);
        if (isNaN(date.getTime())) return dateTime;
        
        var year = date.getFullYear();
        var month = String(date.getMonth() + 1).padStart(2, '0');
        var day = String(date.getDate()).padStart(2, '0');
        var hours = String(date.getHours()).padStart(2, '0');
        var minutes = String(date.getMinutes()).padStart(2, '0');
        
        return `${year}-${month}-${day} ${hours}:${minutes}`;
    } catch (e) {
        return dateTime;
    }
}

// 页面加载完成后自动执行查询
layui.use(['form', 'layer'], function(){
    var form = layui.form;
    var layer = layui.layer;
    
    console.log('Layui表单和弹窗模块初始化完成');
    console.log('Layui版本:', layui.v);
    console.log('Layer模块状态:', layer ? '已加载' : '未加载');
    console.log('Form模块状态:', form ? '已加载' : '未加载');
    
    // 检查Layui是否可用
    if (typeof layui === 'undefined') {
        console.error('Layui未加载！');
        alert('Layui未加载，请检查页面引用');
        return;
    }
    
    // 检查layer模块是否可用
    if (typeof layui.layer === 'undefined') {
        console.warn('Layer模块未直接可用');
    } else {
        console.log('Layer模块直接可用:', layui.layer);
        console.log('Layer.open方法:', typeof layui.layer.open);
    }
    
    // 检查jQuery兼容性
    if (typeof $ !== 'undefined') {
        console.log('jQuery版本:', $.fn.jquery);
        console.log('jQuery对象状态:', $ ? '已加载' : '未加载');
        
        // 检查jQuery方法是否可用
        if (typeof $.fn.parents === 'function') {
            console.log('jQuery parents方法可用');
        } else {
            console.warn('jQuery parents方法不可用，可能存在版本冲突');
        }
    } else {
        console.warn('jQuery未加载');
    }
    
    // 注释掉Layui的复选框事件监听，使用直接的onchange事件
    /*
    // 监听全选
    form.on('checkbox(allSelect)', function(data){
        // 这个事件现在由handleAllSelect函数处理
    });
    
    // 监听单个选择
    form.on('checkbox(workTaskSelect)', function(data){
        // 这个事件现在由handleTaskSelect函数处理
    });
    */
    
    // 监听每页大小变化
    form.on('select(pageSize)', function(data){
        pageSize = parseInt(data.value);
        currentPage = 1;
        loadWorkTaskData();
    });
    
    // 页面加载完成后自动执行查询
    setTimeout(function() {
        console.log('页面加载完成，开始加载任务数据...');
        loadWorkTaskData();
    }, 100);
});

// ========== 编辑任务相关函数 ==========

// 全局变量
var currentEditTask = null;
var selectedRoleIds = [];
var selectedDefectiveItemIds = [];
var roleData = [];
var defectiveData = [];

// 根据ID编辑任务
function editWorkTaskById(taskId) {
    // 查找任务数据
    var taskRow = document.querySelector(`tr[data-task-id="${taskId}"]`);
    if (!taskRow) {
        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.msg('未找到任务数据');
        });
        return;
    }
    
    // 从表格行中提取任务数据
    var task = extractTaskDataFromRow(taskRow);
    if (task) {
        showEditModal(task);
    }
}

// 从表格行中提取任务数据
function extractTaskDataFromRow(row) {
    try {
        var cells = row.cells;
        var task = {
            id: row.getAttribute('data-task-id'),
            processName: cells[1].textContent.trim(),
            processNumber: cells[2].textContent.trim(),
            reportingPermissions: cells[3].textContent.trim(),
            reportingRatio: cells[4].textContent.trim(),
            defectiveItemList: cells[5].textContent.trim(),
            allocationList: cells[6].textContent.trim(),
            plannedStartTime: cells[7].textContent.trim(),
            plannedEndTime: cells[8].textContent.trim(),
            plannedQuantity: cells[9].textContent.trim(),
            goodQuantity: cells[10].textContent.trim(),
            defectiveQuantity: cells[11].textContent.trim(),
            status: cells[12].textContent.trim(),
            creationTime: cells[13].textContent.trim()
        };
        return task;
    } catch (e) {
        console.error('提取任务数据失败:', e);
        return null;
    }
}

// 显示编辑弹窗
function showEditModal(task) {
    currentEditTask = task;
    
    // 填充表单数据
    document.getElementById('editProcessName').value = task.processName || '';
    document.getElementById('editProcessNumber').value = task.processNumber || '';
    document.getElementById('editReportingRatio').value = task.reportingRatio || '';
    document.getElementById('editPlannedQuantity').value = task.plannedQuantity || '';
    document.getElementById('editAllocationList').value = task.allocationList || '';
    document.getElementById('editPlannedStartTime').value = task.plannedStartTime || '';
    document.getElementById('editPlannedEndTime').value = task.plannedEndTime || '';
    document.getElementById('editGoodQuantity').value = task.goodQuantity || '';
    document.getElementById('editDefectiveQuantity').value = task.defectiveQuantity || '';
    document.getElementById('editActualStartTime').value = task.actualStartTime || '';
    document.getElementById('editActualEndTime').value = task.actualEndTime || '';
    document.getElementById('editCreationTime').value = task.creationTime || '';
    document.getElementById('editCreator').value = task.creator || '';
    
    // 处理报工权限
    var permissionsText = task.reportingPermissions || '';
    var permissionsIds = extractIdsFromText(permissionsText);
    selectedRoleIds = permissionsIds;
    document.getElementById('editReportingPermissions').value = formatReportingPermissionsForDisplay(permissionsText);
    document.getElementById('editReportingPermissionsIds').value = permissionsIds.join(',');
    
    // 处理不良品项列表
    var defectiveText = task.defectiveItemList || '';
    var defectiveIds = extractIdsFromText(defectiveText);
    selectedDefectiveItemIds = defectiveIds;
    document.getElementById('editDefectiveItemList').value = formatDefectiveItemsForDisplay(defectiveText);
    document.getElementById('editDefectiveItemIds').value = defectiveIds.join(',');
    
    // 显示弹窗 - 使用更稳定的方式
    console.log('准备显示编辑弹窗...');
    
    // 检查Layui是否可用
    if (typeof layui === 'undefined') {
        alert('Layui未加载，请检查页面引用');
        return;
    }
    
    // 检查layer模块是否可用
    if (typeof layui.layer === 'undefined') {
        console.log('Layer模块未直接可用，尝试使用layui.use加载');
        
        layui.use(['layer'], function(){
            var layer = layui.layer;
            console.log('Layer模块加载成功:', layer);
            
            if (layer && typeof layer.open === 'function') {
                var index = layer.open({
                    type: 1,
                    title: '编辑任务',
                    content: document.getElementById('editWorkTaskModal'),
                    area: ['800px', '600px'],
                    maxmin: true,
                    resize: false,
                    success: function(layero, index) {
                        console.log('编辑弹窗显示成功，索引:', index);
                        // 重新渲染表单
                        layui.form.render();
                    },
                    end: function() {
                        console.log('编辑弹窗关闭');
                    }
                });
                
                console.log('编辑弹窗索引:', index);
            } else {
                alert('Layer模块加载失败，layer.open方法不可用');
            }
        });
    } else {
        console.log('Layer模块直接可用:', layui.layer);
        
        // 直接使用layer
        var index = layui.layer.open({
            type: 1,
            title: '编辑任务',
            content: document.getElementById('editWorkTaskModal'),
            area: ['800px', '600px'],
            maxmin: true,
            resize: false,
            success: function(layero, index) {
                console.log('编辑弹窗显示成功，索引:', index);
                // 重新渲染表单
                layui.form.render();
            },
            end: function() {
                console.log('编辑弹窗关闭');
            }
        });
        
        console.log('编辑弹窗索引:', index);
    }
}

// 从文本中提取ID
function extractIdsFromText(text) {
    if (!text) return [];
    try {
        // 提取数字ID
        var matches = text.match(/\d+/g);
        return matches ? matches.map(id => parseInt(id)) : [];
    } catch (e) {
        console.error('提取ID失败:', e);
        return [];
    }
}

// 格式化报工权限显示
function formatReportingPermissionsForDisplay(text) {
    if (!text) return '';
    try {
        var items = text.split(',').map(s => s.trim()).filter(Boolean);
        return items.join(', ');
    } catch (e) {
        return text;
    }
}

// 格式化不良品项显示
function formatDefectiveItemsForDisplay(text) {
    if (!text) return '';
    try {
        var items = text.split(',').map(s => s.trim()).filter(Boolean);
        return items.join(', ');
    } catch (e) {
        return text;
    }
}

// 显示角色选择弹窗
function showRoleSelectModal() {
    if (roleData.length === 0) {
        loadRoleData();
    } else {
        renderRoleList();
    }
    
    // 显示弹窗 - 使用更稳定的方式
    try {
        layui.use(['layer'], function(){
            var layer = layui.layer;
            console.log('显示角色选择弹窗');
            
            var index = layer.open({
                type: 1,
                title: '选择报工权限',
                content: document.getElementById('roleSelectModal'),
                area: ['500px', '400px'],
                maxmin: true,
                resize: false,
                success: function(layero, index) {
                    console.log('角色选择弹窗显示成功');
                    // 重新渲染表单
                    layui.form.render();
                }
            });
        });
    } catch (error) {
        console.error('显示角色选择弹窗失败:', error);
        alert('弹窗显示失败，请检查Layui是否正确加载');
    }
}

// 加载角色数据
function loadRoleData() {
    fetch('/WorkTask/GetRoleAll')
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                roleData = data.data || [];
                renderRoleList();
            } else {
                layui.use(['layer'], function(){
                var layer = layui.layer;
                layer.msg('加载角色数据失败: ' + data.msg);
            });
            }
        })
        .catch(error => {
            console.error('加载角色数据失败:', error);
            layui.use(['layer'], function(){
                var layer = layui.layer;
                layer.msg('加载角色数据失败');
            });
        });
}

// 渲染角色列表
function renderRoleList() {
    var roleListDiv = document.getElementById('roleList');
    var html = '';
    
    if (roleData.length === 0) {
        html = '<p style="text-align: center; color: #999;">暂无角色数据</p>';
    } else {
        roleData.forEach(role => {
            var isSelected = selectedRoleIds.includes(role.id);
            html += `
                <div class="layui-form-item">
                    <input type="checkbox" name="role_${role.id}" value="${role.id}" 
                           ${isSelected ? 'checked' : ''} 
                           lay-skin="primary" 
                           title="${role.roleName || '角色' + role.id}">
                </div>
            `;
        });
    }
    
    roleListDiv.innerHTML = html;
    layui.form.render('checkbox');
}

// 确认角色选择
function confirmRoleSelection() {
    var checkboxes = document.querySelectorAll('#roleList input[type="checkbox"]:checked');
    selectedRoleIds = Array.from(checkboxes).map(cb => parseInt(cb.value));
    
    // 更新显示
    var roleNames = selectedRoleIds.map(id => {
        var role = roleData.find(r => r.id === id);
        return role ? role.roleName : id;
    });
    
    document.getElementById('editReportingPermissions').value = roleNames.join(', ');
    document.getElementById('editReportingPermissionsIds').value = selectedRoleIds.join(',');
    
    closeRoleSelectModal();
}

// 关闭角色选择弹窗
function closeRoleSelectModal() {
    layui.use(['layer'], function(){
        var layer = layui.layer;
        layer.closeAll();
    });
}

// 显示不良品项选择弹窗
function showDefectiveSelectModal() {
    if (defectiveData.length === 0) {
        loadDefectiveData();
    } else {
        renderDefectiveList();
    }
    
    // 显示弹窗 - 使用更稳定的方式
    try {
        layui.use(['layer'], function(){
            var layer = layui.layer;
            console.log('显示不良品项选择弹窗');
            
            var index = layer.open({
                type: 1,
                title: '选择不良品项',
                content: document.getElementById('defectiveSelectModal'),
                area: ['600px', '500px'],
                maxmin: true,
                resize: false,
                success: function(layero, index) {
                    console.log('不良品项选择弹窗显示成功');
                    // 重新渲染表单
                    layui.form.render();
                }
            });
        });
    } catch (error) {
        console.error('显示不良品项选择弹窗失败:', error);
        alert('弹窗显示失败，请检查Layui是否正确加载');
    }
}

// 加载不良品项数据
function loadDefectiveData() {
    fetch('/WorkTask/GetDefectiveList?index=1&size=100')
        .then(response => response.json())
        .then(data => {
            if (data.code === 200) {
                defectiveData = data.pageData || [];
                renderDefectiveList();
            } else {
                layui.use(['layer'], function(){
                    var layer = layui.layer;
                    layer.msg('加载不良品项数据失败: ' + data.msg);
                });
            }
        })
        .catch(error => {
            console.error('加载不良品项数据失败:', error);
            layui.use(['layer'], function(){
                var layer = layui.layer;
                layer.msg('加载不良品项数据失败');
            });
        });
}

// 渲染不良品项列表
function renderDefectiveList() {
    var defectiveListDiv = document.getElementById('defectiveList');
    var html = '';
    
    if (defectiveData.length === 0) {
        html = '<p style="text-align: center; color: #999;">暂无不良品项数据</p>';
    } else {
        defectiveData.forEach(item => {
            var isSelected = selectedDefectiveItemIds.includes(item.id);
            html += `
                <div class="layui-form-item">
                    <input type="checkbox" name="defective_${item.id}" value="${item.id}" 
                           ${isSelected ? 'checked' : ''} 
                           lay-skin="primary" 
                           title="${item.defectiveCode || ''} | ${item.defectiveName || ''}">
                </div>
            `;
        });
    }
    
    defectiveListDiv.innerHTML = html;
    layui.form.render('checkbox');
}

// 确认不良品项选择
function confirmDefectiveSelection() {
    var checkboxes = document.querySelectorAll('#defectiveList input[type="checkbox"]:checked');
    selectedDefectiveItemIds = Array.from(checkboxes).map(cb => parseInt(cb.value));
    
    // 更新显示
    var defectiveItems = selectedDefectiveItemIds.map(id => {
        var item = defectiveData.find(d => d.id === id);
        return item ? `${item.defectiveCode} | ${item.defectiveName}` : id;
    });
    
    document.getElementById('editDefectiveItemList').value = defectiveItems.join(', ');
    document.getElementById('editDefectiveItemIds').value = selectedDefectiveItemIds.join(',');
    
    closeDefectiveSelectModal();
}

// 关闭不良品项选择弹窗
function closeDefectiveSelectModal() {
    layui.use(['layer'], function(){
        var layer = layui.layer;
        layer.closeAll();
    });
}

// 保存编辑的任务
function saveEditWorkTask() {
    if (!currentEditTask) {
        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.msg('没有要保存的任务数据');
        });
        return;
    }
    
    // 验证必填字段
    var plannedQuantity = document.getElementById('editPlannedQuantity').value;
    var reportingRatio = document.getElementById('editReportingRatio').value;
    
    if (!plannedQuantity || plannedQuantity <= 0) {
        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.msg('请输入有效的计划数量');
        });
        return;
    }
    
    if (!reportingRatio || reportingRatio <= 0) {
        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.msg('请输入有效的报工数配比');
        });
        return;
    }
    
    // 构建更新数据
    var updateData = {
        id: parseInt(currentEditTask.id),
        processId: parseInt(currentEditTask.processId) || 0,
        allocationList: document.getElementById('editAllocationList').value,
        plannedStartTime: document.getElementById('editPlannedStartTime').value,
        plannedEndTime: document.getElementById('editPlannedEndTime').value,
        plannedQuantity: parseInt(plannedQuantity),
        goodQuantity: parseInt(document.getElementById('editGoodQuantity').value) || 0,
        defectiveQuantity: parseInt(document.getElementById('editDefectiveQuantity').value) || 0,
        actualStartTime: document.getElementById('editActualStartTime').value,
        actualEndTime: document.getElementById('editActualEndTime').value,
        updator: 'admin' // 这里可以从登录用户信息中获取
    };
    
    console.log('更新任务数据:', updateData);
    
    // 调用更新API
    fetch('/WorkTask/UpdateWorkTask', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(updateData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.code === 200) {
            layui.use(['layer'], function(){
                var layer = layui.layer;
                layer.msg('更新成功');
            });
            closeEditModal();
            loadWorkTaskData(); // 刷新列表
        } else {
            layui.use(['layer'], function(){
                var layer = layui.layer;
                layer.msg('更新失败: ' + data.msg);
            });
        }
    })
    .catch(error => {
        console.error('更新任务失败:', error);
        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.msg('更新失败: ' + error.message);
        });
    });
}

// 关闭编辑弹窗
function closeEditModal() {
    layui.use(['layer'], function(){
        var layer = layui.layer;
        layer.closeAll();
    });
    currentEditTask = null;
    selectedRoleIds = [];
    selectedDefectiveItemIds = [];
}

// 编辑任务（通过选择行）
function editWorkTask() {
    if (selectedWorkTaskIds.length === 0) {
        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.msg('请选择要编辑的任务');
        });
        return;
    }
    
    if (selectedWorkTaskIds.length > 1) {
        layui.use(['layer'], function(){
            var layer = layui.layer;
            layer.msg('只能选择一个任务进行编辑');
        });
        return;
    }
    
    var taskId = selectedWorkTaskIds[0];
    editWorkTaskById(taskId);
}
</script> 